package com.aliwo.controller;

import com.aliwo.service.ProductOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xuyayuan
 * @data 2021年07月10日
 */
@RestController
@RequestMapping("/api/v1/order")
public class ProductOrderController {

    @Autowired
    private ProductOrderService productOrderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("save")
    @HystrixCommand(fallbackMethod = "saveThrowException") // 当此接口出错的时候回调saveThrowException方法，进行熔断处理
    public Object saveProductOrder(@RequestParam("user_id") Integer userId,
                                   @RequestParam("product_id") Integer productId
                                   , HttpServletRequest request) {
        Object object = productOrderService.saveProductOrder(userId, productId);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", object);
        map.put("msg", "sucess");
        return map;
    }


    /**
     * @param userId
     * @param productId
     * @return 熔断处理，当下订单出错的时候，进行一个熔断操作
     * 需要注意
     * 编写fallback方法实现，方法签名一定要和api方法签名一致（注意点！！！）
     */
    public Object saveThrowException(Integer userId, Integer productId, HttpServletRequest request) {
        String sendProductKey = "save-productOrder-key";
        String sendValue = stringRedisTemplate.opsForValue().get(sendProductKey);
        String ip = request.getRemoteAddr();
        new Thread(() -> {
            if (StringUtils.isBlank(sendValue)) {
                System.out.println("紧急短信，用户下单失败，请离开查找原因,ip地址是=" + ip);
                //发送一个http请求，调用短信服务 TODO
                stringRedisTemplate.opsForValue().set(sendProductKey, "save-order-fail", 20, TimeUnit.SECONDS);
            } else {
                System.out.println("已经发送过短信，20秒内不重复发送");
            }
        }).start();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", null);
        map.put("msg", "抢单服务火爆，在排队中,请稍等!");
        return map;
    }
}
